package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-02-24 17:53
 **/
public class LeetCode1706 {

    public int[] findBall(int[][] grid) {
        int n = grid[0].length;
        int[] ans = new int[n];
        //遍历每个起点
        for (int i = 0; i < n; i++) {
            // 球的初始列
            int col = i;
            for (int[] row : grid) {
                //起始位置的值
                int dir = row[col];
                //由dir决定偏移的方向
                col += dir;

                // 到达侧边或 V 形
                if (col < 0 || col >= n || row[col] != dir) {
                    col = -1;
                    break;
                }
            }
            // col >= 0 为成功到达底部
            ans[i] = col;
        }
        return ans;
    }

}
